#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import json
import requests
from flask import Flask, request, jsonify, render_template, Response
from flask_cors import CORS

app = Flask(__name__, static_folder='static', template_folder='templates')
CORS(app)  # 启用跨域支持

# Deepseek API配置
DEEPSEEK_API_URL = "http://192.168.169.221:1025/generate"
DEFAULT_PARAMS = {
    "max_tokens": 1024,
    "stream": False,
    "do_sample": True,
    "repetition_penalty": 1.00,
    "temperature": 0.7,
    "top_p": 0.9,
    "top_k": 40,
    "model": "qwen"
}

@app.route('/')
def index():
    """返回聊天界面"""
    return render_template('index.html')

@app.route('/api/chat', methods=['POST'])
def chat():
    """处理聊天请求"""
    try:
        # 获取请求数据
        data = request.json
        if not data or 'prompt' not in data:
            return jsonify({"error": "Missing prompt parameter"}), 400
        
        # 合并默认参数和用户参数
        params = DEFAULT_PARAMS.copy()
        params.update(data)
        
        # 发送请求到Deepseek API
        response = requests.post(
            DEEPSEEK_API_URL, 
            json=params,
            headers={"Content-Type": "application/json"},
            timeout=60  # 设置60秒超时
        )
        
        # 处理响应
        response.raise_for_status()  # 抛出HTTP错误
        result = response.json()
        
        # 如果API返回错误，传递错误信息
        if 'error' in result:
            return jsonify({"error": result['error']}), 400
        
        # 返回结果
        return jsonify(result)
    
    except requests.RequestException as e:
        return jsonify({"error": f"API请求失败: {str(e)}"}), 500
    except Exception as e:
        return jsonify({"error": f"服务器错误: {str(e)}"}), 500

@app.route('/api/settings', methods=['GET'])
def get_settings():
    """获取默认设置"""
    return jsonify(DEFAULT_PARAMS)

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5001))
    app.run(host='0.0.0.0', port=port, debug=True) 